//
//  HDApplyIndemnityFirstVC.swift
//  HuaDaoPeifu
//
//  Created by ZERO on 2018/7/20.
//  Copyright © 2018年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD

class HDApplyIndemnityFirstVC: UIViewController,UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var changeView: UIView!

    @IBOutlet weak var personLabel: UILabel!
    @IBOutlet weak var indemnityLabel: UILabel!
    @IBOutlet weak var relationLabel: UILabel!
    @IBOutlet weak var numberLabel: UILabel!
    
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var genderLabel: UILabel!
    @IBOutlet weak var IDNumberLabel: UILabel!
    @IBOutlet weak var phoneLabel: UILabel!

    @IBOutlet weak var accountNameLabel: UILabel!
    @IBOutlet weak var cardNumberLabel: UILabel!
    @IBOutlet weak var bankNameLabel: UILabel!
    @IBOutlet weak var branchLabel: UILabel!
    
    @IBOutlet weak var IDTypeLabel: UILabel!

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var viewHeight: NSLayoutConstraint!   // 证件类型view高度
    @IBOutlet weak var bgViewHeight: NSLayoutConstraint! // 滑动高度
    
    @IBOutlet weak var nextBtn1: UIButton!
    
    
    var dataArray: [String] = []
    var casemodel = HDCaseModel()
    var info_id = String()
    var policyno = String()
    
    var partone = HDRecognizeeDetailModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "速赔宝"
        setUI()
        getdata()
    }

    func setUI(){
        self.changeView.layer.shadowOffset = CGSize(width: 1, height: 4)
        self.changeView.layer.shadowColor = UIColor.lightGray.cgColor
        self.changeView.layer.shadowOpacity = 0.4
        self.changeView.layer.cornerRadius = 3
        nextBtn1.layer.cornerRadius = 3
        
        collectionView?.delegate = self
        collectionView?.dataSource = self
        collectionView?.isScrollEnabled = false
        collectionView?.register(ImageCollectionCell.self, forCellWithReuseIdentifier: "ImageCollectionCell");
        
    }
    
    func getdata(){
        
//        HDApiManagerHandler.requestInitCase(self.policyno as String) { (model:HDCaseModel?) in
//
//        }
        HDApiManagerHandler.requestDefaultRecognizee("", casemodel.case_id) {[unowned self] (result:HDApiResult?) in
            
            guard let result = result,
            let recognizee = result.data else {
                SVProgressHUD .showError("哦，网络出错了！")
                return
            }
            
            let r = recognizee as! HDRecognizeeModel
            
            if r.status == "1"{
//                 去选择被保人
                let vc = HDRecognizeeVC()
                vc.title = "选择被保人"
                vc.selectRecognizeeCompletionHandler = {[unowned self]
                    (recognizee:HDRecognizeeModel) in
                    self.getInfoData(model: recognizee)
                }
                
                self.navigationController?.pushViewController(vc, animated: true)
            }
            else if r.status == "2"{
                self.getInfoData(model: result.data as! HDRecognizeeModel)
            }
            
        }
        
    }
    
    func getInfoData(model: HDRecognizeeModel) {
        self.info_id = model.id
        
        personLabel.text = model.partone?.name
        indemnityLabel.text = model.partone?.name
        relationLabel.text = model.relation=="1" ? "本人" : ""
        numberLabel.text = model.partone?.critcode
        
        nameLabel.text = model.partone?.name
        genderLabel.text = model.partone?.sex=="1" ? "男" : "女"
        IDNumberLabel.text = model.partone?.critcode
        phoneLabel.text = model.partone?.phone
        
        accountNameLabel.text = model.partone?.account_name
        cardNumberLabel.text = model.partone?.accountno
        bankNameLabel.text = model.partone?.bank
        branchLabel.text = model.partone?.subBranch
        if let partone = model.partone  {
            self.partone = model.partone!
            IDTypeLabel.text = getIDTypeName(IDNumber: partone.crittype)
        }
        
        if let subStrings = model.partone?.images.split(separator: ","),
            let urls = cropImageUrls(subStrings) {
            self.dataArray = urls
        }
        
        let rowcount = self.dataArray.count / 2 as NSInteger
        let imageHeight = (AppConstant.screenWidth - 16 - 30)/2.0 * 5/8 as CGFloat

        viewHeight.constant =  imageHeight * CGFloat(rowcount + 1) + 10 * CGFloat(rowcount) + 71
        bgViewHeight.constant = 772 + viewHeight.constant
        scrollView.contentSize = CGSize(width:0, height: bgViewHeight.constant)
        collectionView.reloadData()
        

    }
    // 根据ID返回身份类型
    func getIDTypeName(IDNumber:String) -> String  {
        if IDNumber == "0" {
            return "身份证"
        }else if IDNumber == "1" {
            return "护照"
        }else if IDNumber == "7" {
            return "出生证"
        }else if IDNumber == "11" {
            return "回乡证"
        }else if IDNumber == "8-1" {
            return "驾驶证"
        }else if IDNumber == "9" {
            return "工号"
        }else if IDNumber == "8-2" {
            return "港澳通行证"
        }else if IDNumber == "4" {
            return "户口本"
        }else if IDNumber == "2" {
            return "军官证"
        }else {
            return "台湾通行证"
        }
}
    // 处理图片链接
    func cropImageUrls(_ relativeUrls:[String.SubSequence]?) -> [String]? {
        guard let relativeUrls = relativeUrls else {
            return nil
        }
        var urls = [String]()
        for url in relativeUrls {
            
            if url.first == "."{
                if url.startIndex != Substring.Index.init(encodedOffset: 0){
                    continue
                }
                urls.append(kBaseApiv2URL + "/picc" + url.substring(from: url.index(url.startIndex, offsetBy: 2)))
            }else {
                urls.append(kBaseApiv2URL + url)
            }
        }
        return urls
    }
    // 更换被保人
    @IBAction func changeAction(_ sender: UIButton) {
        //                 去选择被保人
        let vc = HDRecognizeeVC()
        vc.title = "选择被保人"
        vc.selectRecognizeeCompletionHandler = {[unowned self]
            (recognizee:HDRecognizeeModel) in
            self.getInfoData(model: recognizee)
        }
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // 下一步
    @IBAction func stepAction(_ sender: UIButton) {
        if  self.info_id == "" {
            SVProgressHUD .showError("请选择本次赔付申请的被保险人")
            return
        }
        
        
        // 关联 case_id 和 info_id
        HDApiManagerHandler.infoAddPartone(self.casemodel.case_id, self.info_id, { (result2) in
            guard let result = result2 else {
                SVProgressHUD .showError("哦，网络出错了！")
                return
            }
            
            if result.status == .Success {
                let applySecondVC = HDApplyIndemnitySecondVC()
                applySecondVC.casemodel = self.casemodel
                applySecondVC.info_id = self.info_id
                applySecondVC.policyno = self.policyno
                applySecondVC.partone = self.partone
                self.navigationController?.pushViewController(applySecondVC, animated: true)
            }else{
                SVProgressHUD .showError(result2?.msg)
            }
         
        })
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let arr = dataArray
        return arr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionCell", for: indexPath) as! ImageCollectionCell
        let str = dataArray[indexPath.row].addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        let url = URL(string: str!)
        cell.imageView?.sd_setImage(with:url, placeholderImage: UIImage(named: ""))
        
        return cell
    }
    
    //每个分区的内边距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(10, 10, 10, 10);
    }
    
    //最小 item 间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10;
    }
    
    //最小行间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10;
    }
    
    //item 的尺寸
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (AppConstant.screenWidth - 16 - 30)/2.0, height: (AppConstant.screenWidth - 16 - 30)/2.0 * 5 / 8)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

class ImageCollectionCell: UICollectionViewCell {
    var imageView:UIImageView?//image
    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initView(){
        imageView = UIImageView(frame: CGRect(x: 5, y: 5, width: self.bounds.width - 10, height: self.bounds.height - 10))
        imageView?.backgroundColor = UIColor.groupTableViewBackground
        self .addSubview(imageView!)
    }
    
   
}
